//
//  NetWorkTools.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/7/30.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit
import AFNetworking

private let TSYErrorDomain = "com.itheima.error.network"

private enum NetworkError: Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    private var errorDescrption: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token 为空"
        }
    }
    
    private func error() ->NSError {
        return NSError(domain:TSYErrorDomain , code: rawValue, userInfo: [TSYErrorDomain:errorDescrption])
    }
}

private enum TSYNetworkMethod: String{
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    private var clientId = "3197511794"
    var redirectUri = "http://www.baidu.com"
    private var clientSecret = "b6d546ecf0b912fc5d379a3b9e5ffb74"
    
    typealias TSYNetFinishedCallBack = (result: [String: AnyObject]?,error: NSError?) -> ()
 
    static let sharedNetworkTools: NetworkTools = {
        let instance = NetworkTools(baseURL: NSURL(string: "https://api.weibo.com/"))
        instance.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return instance
    }()
    
    private func tokenDict(finished: TSYNetFinishedCallBack) -> [String: AnyObject]? {
        if UserAccount.loadAccount()?.access_token == nil {
            
            finished(result: nil, error: NetworkError.emptyTokenError.error())
            return nil
        }
         return ["access_token":UserAccount.loadAccount()!.access_token!]
    
    }
    
    //MARK:- 加载微博数据
    func loadStatus(finished: TSYNetFinishedCallBack) {
        guard let params = tokenDict(finished) else {
            return
        }
        
        let urlString = "2/statuses/friends_timeline.json"
        
        request(TSYNetworkMethod.GET, urlString: urlString, params: params, finished:finished)

    }
    
    //MARK:-加载用户数据
    func loadUserInfo(uid:String,finished: TSYNetFinishedCallBack) {
        
        guard var params = tokenDict(finished) else {
            return
        }
        params["uid"] = uid
        
        let urlString = "2/users/show.json"

        request(TSYNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
        
    }
    
    //授权 URL
    var oauthURL: NSURL {
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")!
    }
    /**
    client_id	true	string	申请应用时分配的AppKey。
    client_secret	true	string	申请应用时分配的AppSecret。
    grant_type	true	string	请求的类型，填写authorization_code
    code	true	string	调用authorize获得的code值。
    redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
    */
    func loadAccessToken(code: String,finished: (result: [String: AnyObject]?,error: NSError?)->())
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id" : clientId, "client_secret" : clientSecret, "grant_type" : "authorization_code", "code" : code, "redirect_uri": redirectUri]
        
           request(TSYNetworkMethod.POST, urlString: urlString, params: params, finished: finished)
    }
    /**
    MARK: -封装AFN网络方法
    
    - parameter method   : HTTP 方法GET/POST
    - parameter urlString: URL 字符串
    - parameter params   : 字典参数
    - parameter finished : 完成回掉
    */
    
    private func request(method: TSYNetworkMethod, urlString: String, params: [String: AnyObject],finished:TSYNetFinishedCallBack) {
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject]{
                finished(result: result,error: nil)
                
            } else {
                finished(result: nil, error: NetworkError.emptyDataError.error())
            }
        }
        
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            finished(result: nil, error: error)
        }
        
        switch method {
        case .GET: GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST: POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }
    
    
}
